// eslint-disable-next-line react-compiler/react-compiler
/* eslint-disable react-hooks/exhaustive-deps */
import { logoutApi, userInfoApi, userMenusApi } from '@/apis/user'
import AuthComponent from '@/components/AuthComponent'
import { IconName } from '@/components/IconComponents'
import Loading from '@/components/Loading'
import { RADIUS, ROUTER_PATHS_PUBLIC, TRANSITION } from '@/constants/global'
import { arrToMulArr } from '@/utils/array'
import useLayoutConfig from '@/zustand/useLayoutConfig'
import useUserInfo from '@/zustand/useUserInfo'
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import { Dropdown, Layout, Menu } from 'antd'
import type { MenuProps } from 'antd/lib'
import { map } from 'lodash'
import { MacScrollbar } from 'mac-scrollbar'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Outlet, useNavigate } from 'react-router-dom'

let timer = 0

export default function MainLayout() {
  /** 👇 路由跳转 👇 */
  const navigate = useNavigate()
  /** 👇 zustand 👇 */
  const clear = useUserInfo((s) => s.clear)
  const token = useUserInfo((s) => s.token)
  const loginInfo = useUserInfo((s) => s.userInfo)
  const setLoginInfo = useUserInfo((s) => s.setUserInfo)
  const setUserMenus = useUserInfo((s) => s.setUserMenus)
  const menuSelectedKeys = useUserInfo((s) => s.menuSelectedKeys)
  /** 👇 页面布局模式 👇 */
  const isFixed = useLayoutConfig((s) => s.isFixed)
  /** 👇 当前主题模式 👇 */
  const themeMode = useLayoutConfig((s) => s.themeMode)
  /** 👇 菜单 👇 */
  const [menus, setMenus] = useState<MenuProps['items']>([])
  /** 👇 侧栏是否收起 👇 */
  const [collapsed, setCollapsed] = useState(false)
  /** 👇 页面初始化是否完成 👇 */
  const [check, setCheck] = useState(false)
  /** 👇 页面的最大宽度 👇 */
  const MAX_W = useMemo(() => (isFixed ? 'max-w-[1400px]' : 'max-w-[100%]'), [isFixed])
  /** 👇 退出登录 👇 */
  const logout = useCallback(() => {
    setCheck(false)
    logoutApi()
      .then(() => {
        clear()
        navigate(ROUTER_PATHS_PUBLIC.LOGIN)
      })
      .catch(() => setCheck(true))
  }, [navigate, clear])
  /** 👇 用户信息, 菜单权限的获取逻辑 👇 */
  useEffect(() => {
    timer = window.setTimeout(() => {
      if (token) {
        console.log('MainLayout:check', check)
        Promise.all([userInfoApi(), userMenusApi()])
          .then(([info, menus]) => {
            setLoginInfo(info)
            setUserMenus(menus)
            const newMenu = map(menus, (c) => {
              const icon = c.icon ? <IconName name={c.icon} /> : undefined
              return { id: c.id, pid: c.pid, key: c.path, label: c.name, icon }
            })
            setMenus(arrToMulArr(newMenu))
            setCheck(true)
          })
          .catch(() => navigate(ROUTER_PATHS_PUBLIC.LOGIN))
      } else navigate(ROUTER_PATHS_PUBLIC.LOGIN)
    }, 10)
    return () => {
      setCheck(false)
      if (timer) window.clearTimeout(timer)
    }
  }, [])

  return check ? (
    <Layout className="h-[100vh]">
      <Layout.Header className="flex justify-center bg-white px-0">
        <Layout className={`px-[8px] ${MAX_W} w-[100%] bg-transparent ${TRANSITION}`}>
          <Layout.Sider
            collapsible
            trigger={null}
            collapsedWidth={65}
            collapsed={collapsed}
            className={`header-sider-logo bg-transparent text-[18px] font-bold`}
          >
            LOGO
          </Layout.Sider>

          <Layout.Content className="flex items-center justify-between bg-transparent">
            <div className="flex h-[100%] items-center">
              <div
                onClick={() => setCollapsed(!collapsed)}
                className={`flex aspect-square h-[100%] items-center justify-center text-[20px] ${TRANSITION} cursor-pointer hover:text-[#1890ff]`}
              >
                {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              </div>
            </div>
            <div>
              <Dropdown menu={{ items: [{ key: '0', label: '退出登录', onClick: logout }] }}>
                <div className="h-[48px] leading-[48px]">
                  <span className="p-[5px]">欢迎您: </span>
                  <span>{loginInfo.userName}</span>
                </div>
              </Dropdown>
            </div>
          </Layout.Content>
        </Layout>
      </Layout.Header>

      <Layout className={`${MAX_W} mx-auto w-[100%] p-[8px] ${TRANSITION} bg-transparent`}>
        <Layout.Sider
          collapsible
          theme={themeMode}
          trigger={null}
          breakpoint="xl"
          collapsedWidth={65}
          collapsed={collapsed}
          onBreakpoint={setCollapsed}
          className={`main-sider ${RADIUS} overflow-hidden`}
        >
          <MacScrollbar className="flex-1" suppressScrollX>
            <Menu
              theme={themeMode}
              mode="inline"
              items={menus}
              inlineIndent={16}
              className={`bg-transparent`}
              onClick={(e) => navigate(e.key)}
              selectedKeys={menuSelectedKeys}
            />
          </MacScrollbar>
        </Layout.Sider>

        <Layout.Content
          className={`ml-[8px] ${RADIUS} flex flex-1 flex-col overflow-hidden bg-white py-[8px]`}
        >
          <MacScrollbar data-name="MacScrollbar" className="h-[100%] px-[8px]" suppressScrollX>
            <AuthComponent>
              <Outlet />
            </AuthComponent>
          </MacScrollbar>
        </Layout.Content>
      </Layout>
    </Layout>
  ) : (
    <Loading />
  )
}
